---
title: Json
sidebar_position: 7
---

# Json

```csharp
public class UserInfo
{
    public string UserName { get; set; }
    public int Age { get; set; }
}
```

### ToObj\<T\>

:::note
字符串转为指定的对象
:::

```csharp
string userInfo = @"
{
    ""userName"": ""ABCD"",
    ""age"": 23
}";
var user = userInfo.ToObj<UserInfo>();
// user.UserName == "ABCD";
// user.Age == 23;
```

### ToObjCollection\<T\>

:::note
字符串转为对象集合
:::

```csharp
string userInfo = @"
[
    {
        ""userName"": ""ABCD"",
        ""age"": 23
    }
]";
IEnumerable<UserInfo> user = userInfo.ToObjCollection<UserInfo>();
// user.First().UserName = "ABCD";
// user.First().Age = 23;
```

### ToJson

:::note
对象转json字符串
:::

```csharp
UserInfo user = new()
{
    UserName = "ABCD",
    Age = 23
};
var jsonString = user.ToJson().Trim();
// "{\"userName\":\"ABCD\",\"age\":23}"
```

### JsonMap

:::note
通过json的序列化反序列化实现的map功能
:::

```csharp
public class UserInfoTwo
{
    public string UserName { get; set; }
    public int Age { get; set; }
}

UserInfo user = new()
{
    UserName = "ABCD",
    Age = 23
};
UserInfoTwo user2 = user.JsonMap<UserInfoTwo>();
```

### JsonNode

:::note
当拿到的 json 对象比较复杂时, 相比于构建对应的 class, 使用 JsonNode 更加方便
:::

```csharp
string userInfo = @"
[
    {
        ""userName"": ""ABCD"",
        ""age"": 23
    }
]";
JsonNode userNode = userInfo.ToJsonNode();
JsonArray userArray = userNode.ToJsonArray();
JsonObject userObject = userNode.ToJsonObject();
```

